package com.mylib.libcore.utils;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.alibaba.android.arouter.launcher.ARouter;
import com.mylib.libcore.AppContext;
import com.mylib.libcore.R;
import com.mylib.libcore.bean.EveryDayCoin;
import com.mylib.libcore.config.CoinTypeEnum;
import com.mylib.libcore.config.RouterConfig;
import com.mylib.widget.datetimepicker.DateTimePicker;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.mylib.libcore.config.AppSPKeyConfig.IS_OPEN_AD;
import static com.mylib.libcore.config.CoinTypeEnum.LOGIN_COIN;

public class UIUtils {

    private static boolean isLogin=false;
    private static boolean isNight=false;
    private static boolean isVip=false;
    /**
     * 跳转到主页面
     */
    public static void goToMainActivity() {
        if(isLogin()){
            ARouter.getInstance().build(RouterConfig.ROUTER_MAIN).navigation();
        }else{
            ARouter.getInstance().build(RouterConfig.ROUTER_ACTIVITY_LOGIN).navigation();
        }
    }

    public static boolean isLogin() {
        String loginState = AppContext.getInstance().getAppPreferencesHelper().getKeyValue("isLogin")+"";
        if(!UIUtils.isEmpty(loginState) && loginState.equals("1")){
            isLogin=true;
        }else {
            isLogin=false;
        }
        return isLogin;
    }
    public static boolean isOpenAD() {
        String loginState = AppContext.getInstance().getAppPreferenceForever().getKeyValue(IS_OPEN_AD)+"";
        if(!UIUtils.isEmpty(loginState) && loginState.equals("1")){
            return true;
        }else {
            return false;
        }
    }
    public static boolean isNight() {
        String loginState = AppContext.getInstance().getAppPreferencesHelper().getKeyValue("isNight")+"";
        if(!UIUtils.isEmpty(loginState) && loginState.equals("1")){
            isNight=true;
        }else {
            isNight=false;
        }
        return isNight;
    }
    public static boolean isVip() {
        String vipState = AppContext.getInstance().getAppPreferencesHelper().getKeyValue("isVip")+"";
        if(!UIUtils.isEmpty(vipState) && vipState.equals("1")){
            isVip=true;
        }else {
            isVip=false;
        }
        return isVip;
    }

    /**
     * 清除每日金币
     * @return
     */
    public static void clearEveryDayCoin(){
        EveryDayCoin coin = new EveryDayCoin();
        coin.setLogin_coin(0);
        coin.setOnline_coin(0);
        coin.setDk_coin(0);
        coin.setSign_coin(0);
        coin.setLl_coin(0);
        coin.setGame_coin(0);
        coin.setNovel_coin(0);
        coin.setTz_coin(0);
        coin.setCg_coin(0);
        coin.setNews_coin(0);
        coin.setWeather_coin(0);
        coin.setVideo_coin(0);
        coin.setBk_coin(0);
        coin.setInvite_coin(0);
        coin.setZs_coin(0);
        coin.setLottery_coin(0);
        coin.setWw_coin(0);
        coin.setRank_coin(0);
        AppContext.getInstance().getAppPreferenceForever().setEveryDayCoin(coin);
    }

    /**
     * 记录领取每日金币
     * @return
     */
    public static void notifyEveryDayCoin(CoinTypeEnum title){
        EveryDayCoin coin = AppContext.getInstance().getAppPreferenceForever().getEveryDayCoin();
        switch (title){
            case LOGIN_COIN:
                coin.setLogin_coin(2);
                break;
            case ON_LINE_COIN:
                coin.setOnline_coin(2);
                break;
            case DK_COIN:
                coin.setDk_coin(2);
                break;
            case SIGN_COIN:
                coin.setSign_coin(2);
                break;
            case LL_COIN:
                coin.setLl_coin(2);
                break;
            case GAME_COIN:
                coin.setGame_coin(2);
                break;
            case NOVEL_COIN:
                coin.setNovel_coin(2);
                break;
            case TZ_COIN:
                coin.setTz_coin(2);
                break;
            case CG_COIN:
                coin.setCg_coin(2);
                break;
            case NEWS_COIN:
                coin.setNews_coin(2);
                break;
            case WEATHER_COIN:
                coin.setWeather_coin(2);
                break;
            case VIDEO_COIN:
                coin.setVideo_coin(2);
                break;
            case BK_COIN:
                coin.setBk_coin(2);
                break;
            case INVITE_COIN:
                coin.setInvite_coin(2);
                break;
            case ZS_COIN:
                coin.setZs_coin(2);
                break;
            case LOTTERY_COIN:
                coin.setLottery_coin(2);
                break;
            case WW_COIN:
                coin.setWw_coin(2);
                break;
            case RANK_COIN:
                coin.setRank_coin(2);
                break;
        }
        AppContext.getInstance().getAppPreferenceForever().setEveryDayCoin(coin);
    }

    /**
     * 清除每日金币
     * @return
     */
    public static void setKeyEveryDayCoin(CoinTypeEnum title){
        EveryDayCoin coin = AppContext.getInstance().getAppPreferenceForever().getEveryDayCoin();
        switch (title){
            case LOGIN_COIN:
                if(coin.getLogin_coin()!= 2)coin.setLogin_coin(1);
                break;
            case ON_LINE_COIN:
                if(coin.getOnline_coin()!= 2)coin.setOnline_coin(1);
                break;
            case DK_COIN:
                if(coin.getDk_coin()!= 2)coin.setDk_coin(1);
                break;
            case SIGN_COIN:
                if(coin.getSign_coin()!= 2)coin.setSign_coin(1);
                break;
            case LL_COIN:
                if(coin.getLl_coin()!= 2)coin.setLl_coin(1);
                break;
            case GAME_COIN:
                if(coin.getGame_coin()!= 2)coin.setGame_coin(1);
                break;
            case NOVEL_COIN:
                if(coin.getNovel_coin()!= 2)coin.setNovel_coin(1);
                break;
            case TZ_COIN:
                if(coin.getTz_coin()!= 2)coin.setTz_coin(1);
                break;
            case CG_COIN:
                if(coin.getCg_coin()!= 2)coin.setCg_coin(1);
                break;
            case NEWS_COIN:
                if(coin.getNews_coin()!= 2)coin.setNews_coin(1);
                break;
            case WEATHER_COIN:
                if(coin.getWeather_coin()!= 2)coin.setWeather_coin(1);
                break;
            case VIDEO_COIN:
                if(coin.getVideo_coin()!= 2)coin.setVideo_coin(1);
                break;
            case BK_COIN:
                if(coin.getBk_coin()!= 2)coin.setBk_coin(1);
                break;
            case INVITE_COIN:
                if(coin.getInvite_coin()!= 2)coin.setInvite_coin(1);
                break;
            case ZS_COIN:
                if(coin.getZs_coin()!= 2)coin.setZs_coin(1);
                break;
            case LOTTERY_COIN:
                if(coin.getLottery_coin()!= 2)coin.setLottery_coin(1);
                break;
            case WW_COIN:
                if(coin.getWw_coin()!= 2)coin.setWw_coin(1);
                break;
            case RANK_COIN:
                if(coin.getRank_coin()!= 2)coin.setRank_coin(1);
                break;
        }
        AppContext.getInstance().getAppPreferenceForever().setEveryDayCoin(coin);
    }

    //定一个静态方法，专门生成单个的号码
    public static String getRandPhoneNum() {
        //给予真实的初始号段，号段是在百度上面查找的真实号段
        String[] start = {"133", "149", "153", "173", "177",
                "180", "181", "189", "199", "130", "131", "132",
                "145", "155", "156", "166", "171", "175", "176", "185", "186", "166", "134", "135",
                "136", "137", "138", "139", "147", "150", "151", "152", "157", "158", "159", "172",
                "178", "182", "183", "184", "187", "188", "198", "170", "171"};

        //随机出真实号段  使用数组的length属性，获得数组长度，
        //通过Math.random（）*数组长度获得数组下标，从而随机出前三位的号段
        String phoneFirstNum = start[(int) (Math.random() * start.length)];
        //随机出剩下的8位数
        String phoneLastNum = "";
        //定义尾号，尾号是8位
        final int LENPHONE = 8;
        //循环剩下的位数
        for (int i = 0; i < LENPHONE; i++) {
            //每次循环都从0~9挑选一个随机数
            phoneLastNum += (int) (Math.random() * 10);
        }
        //最终将号段和尾数连接起来
        String phone =  phoneFirstNum + phoneLastNum;
        if(phone.length() != 11)phone = "15767763821";
       return phone;

    }


    /**
     * string小时转int
     */
    public static int hourTextToInt(String hourText){
        if(isEmpty(hourText)){
            return 0;
        }

        String hour="";
        if(hourText.length()>1 && hourText.substring(0,1).equals("0")){
            hour  = hourText.replace("0","");
        }else {
            hour = hourText;
        }

        if(isEmpty(hour)){
            return 0;
        }else {
            return Integer.parseInt(hour);
        }

    }



    /**
     * 字符串截取某个字符之后的字符
     * @return
     */
    public static String getTextIntercept(String data,int Mark){

      return data.substring(Mark);
    }



    //日期选择器
    public static void showDateDialog(Context context, TextView textView) {

       // Date endDate = new Date();
        DateTimePicker dateTimePicker = new DateTimePicker.Builder(context)
                .setCancelTextColor(context.getResources().getColor(R.color.text_black))
                .setOkTextColor(context.getResources().getColor(R.color.button_blue_normal))
                .setTitleTextColor(context.getResources().getColor(R.color.text_gray))
                .setTextColor(context.getResources().getColor(R.color.text_gray))
                .setSelectedTextColor(context.getResources().getColor(R.color.text_black))
                .setDividerColor(context.getResources().getColor(R.color.line_color))
                .setDividerWidth(2f)
                .setKeepLastSelected(true)
                .setShowYMDHMLabel(false)
                .setTextSize(context.getResources().getDimensionPixelSize(R.dimen.text_30px), context.getResources().getDimensionPixelSize(R.dimen.text_30px))
                .setShowType(DateTimePicker.ShowType.DAY)
//                .setStartDate(startData)
//                .setEndDate(endDate)
                .build();
        dateTimePicker.setResultHandler(date -> textView.setText(TimeUtils.getDateTime(date)));
        dateTimePicker.show(new Date());
    }

    //时间时分选择器
    public static void showTimeDialog(Context context, TextView textView) {
        try {
            // Date endDate = new Date();
            DateTimePicker dateTimePicker = new DateTimePicker.Builder(context)
                    .setCancelTextColor(context.getResources().getColor(R.color.text_black))
                    .setOkTextColor(context.getResources().getColor(R.color.button_blue_normal))
                    .setTitleTextColor(context.getResources().getColor(R.color.text_gray))
                    .setTextColor(context.getResources().getColor(R.color.text_gray))
                    .setSelectedTextColor(context.getResources().getColor(R.color.text_black))
                    .setDividerColor(context.getResources().getColor(R.color.line_color))
                    .setDividerWidth(2f)
                    .setKeepLastSelected(true)
                    .setShowYMDHMLabel(false)
                    .setTextSize(context.getResources().getDimensionPixelSize(R.dimen.sp_14), context.getResources().getDimensionPixelSize(R.dimen.sp_14))
                    .setShowType(DateTimePicker.ShowType.ONLY_HOUR_MINUTE)
//                .setStartDate(startData)
//                .setEndDate(endDate)
                    .build();
            dateTimePicker.setResultHandler(date -> textView.setText(date.getHours()+":"+date.getMinutes()));
            dateTimePicker.show(new Date());
        }catch (Exception e){

        }
    }

    //闹钟选择器
    public static void showHourTimeDialog(Context context, TextView textView) {
        try {
            DateTimePicker dateTimePicker = new DateTimePicker.Builder(context)
                    .setCancelTextColor(context.getResources().getColor(R.color.text_black))
                    .setOkTextColor(context.getResources().getColor(R.color.button_blue_normal))
                    .setTitleTextColor(context.getResources().getColor(R.color.text_gray))
                    .setTextColor(context.getResources().getColor(R.color.text_gray))
                    .setSelectedTextColor(context.getResources().getColor(R.color.text_black))
                    .setDividerColor(context.getResources().getColor(R.color.line_color))
                    .setDividerWidth(2f)
                    .setKeepLastSelected(true)
                    .setShowYMDHMLabel(true)
                    .setTextSize(context.getResources().getDimensionPixelSize(R.dimen.sp_14), context.getResources().getDimensionPixelSize(R.dimen.sp_14))
                    .setShowType(DateTimePicker.ShowType.MINUTE)
                   // .setStartDate(startData)
//                .setEndDate(endDate)
                    .build();
            dateTimePicker.setResultHandler(date ->textView.setText(TimeUtils.getDateTimeHour(date)));
            dateTimePicker.show(new Date());
        }catch (Exception e){

        }
    }

    //闹钟选择器
    public static void showClockDialog(Context context, TextView textView) {
        try {
            Date startData = new Date();
            DateTimePicker dateTimePicker = new DateTimePicker.Builder(context)
                    .setCancelTextColor(context.getResources().getColor(R.color.text_black))
                    .setOkTextColor(context.getResources().getColor(R.color.button_blue_normal))
                    .setTitleTextColor(context.getResources().getColor(R.color.text_gray))
                    .setTextColor(context.getResources().getColor(R.color.text_gray))
                    .setSelectedTextColor(context.getResources().getColor(R.color.text_black))
                    .setDividerColor(context.getResources().getColor(R.color.line_color))
                    .setDividerWidth(2f)
                    .setKeepLastSelected(true)
                    .setShowYMDHMLabel(true)
                    .setTextSize(context.getResources().getDimensionPixelSize(R.dimen.sp_14), context.getResources().getDimensionPixelSize(R.dimen.sp_14))
                    .setShowType(DateTimePicker.ShowType.MINUTE)
                .setStartDate(startData)
//                .setEndDate(endDate)
                    .build();
            dateTimePicker.setResultHandler(date ->textView.setText(TimeUtils.getDateTimeHour(date)));
            dateTimePicker.show(new Date());
        }catch (Exception e){

        }
    }



    /**
     * 获取手机厂商
     * @return
     */
    public static String toString(int number){
       return number+"";

    }

    /**
     * 获取手机厂商
     * @return
     */
    public static String getPhone(){
        String name = Build.MANUFACTURER;
        if (!UIUtils.isEmpty(name)){
            return name;
        }else {
            return "";
        }

    }
    public static boolean isWeixinAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }

    public static boolean checkAliPayInstalled(Context context) {
        Uri uri = Uri.parse("alipays://platformapi/startApp");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        ComponentName componentName = intent.resolveActivity(context.getPackageManager());
        return componentName != null;
    }


    public static void setmargin(View v, int l, int t, int r, int b) {
        if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
            p.setMargins(l, t, r, b);
            v.requestLayout();
        }
    }



    /**
     * 非空判断
     */
    public static boolean isEmpty(Object obj) {

        if (obj == null) {
            return true;
        }

        if (obj instanceof Collection<?>) {
            // 检查各种Collection是否为空(List,Queue,Set)
            return ((Collection<?>) obj).isEmpty();
        } else if (obj instanceof Map<?, ?>) {
            // 检查各种Map
            return ((Map<?, ?>) obj).isEmpty();
        } else if (obj instanceof CharSequence) {
            // 检查各种CharSequence
            return ((CharSequence) obj).length() == 0;
        } else if (obj.getClass().isArray()) {
            // 检查各种base array
            // return Array.getLength(obj) == 0;
            if (obj instanceof Object[]) {
                return ((Object[]) obj).length == 0;
            } else if (obj instanceof int[]) {
                return ((int[]) obj).length == 0;
            } else if (obj instanceof long[]) {
                return ((long[]) obj).length == 0;
            } else if (obj instanceof short[]) {
                return ((short[]) obj).length == 0;
            } else if (obj instanceof double[]) {
                return ((double[]) obj).length == 0;
            } else if (obj instanceof float[]) {
                return ((float[]) obj).length == 0;
            } else if (obj instanceof boolean[]) {
                return ((boolean[]) obj).length == 0;
            } else if (obj instanceof char[]) {
                return ((char[]) obj).length == 0;
            } else if (obj instanceof byte[]) {
                return ((byte[]) obj).length == 0;
            }
        }
        return false;
    }



    /********防止重复请求********/
    private static long lastRequestTime;
    public synchronized static boolean isFastRequest() {
        long time = System.currentTimeMillis();
        if (time - lastRequestTime < 700) {
            return true;
        }
        lastRequestTime = time;
        return false;
    }

    /********防止按钮连续点击********/
    private static long lastClickTime;
    public synchronized static boolean isFastClick() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < 500) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    public static void  fullScreen(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                //5.x开始需要把颜色设置透明，否则导航栏会呈现系统默认的浅灰色
                Window window = activity.getWindow();
                View decorView = window.getDecorView();
                //两个 flag 要结合使用，表示让应用的主体内容占用系统状态栏的空间
                int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
                decorView.setSystemUiVisibility(option);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
                //导航栏颜色也可以正常设置
//                window.setNavigationBarColor(Color.TRANSPARENT);
            } else {
                Window window = activity.getWindow();
                WindowManager.LayoutParams attributes = window.getAttributes();
                int flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
                int flagTranslucentNavigation = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
                attributes.flags |= flagTranslucentStatus;
//                attributes.flags |= flagTranslucentNavigation;
                window.setAttributes(attributes);
            }
        }
    }
    //dp转换成像素
    public static int dp2px(int value ) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value,AppContext.getInstance().getContext().getResources().getDisplayMetrics() );
    }

    //像素转换成dp
    public static int dp2sp(int value ) {
        return (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, value,AppContext.getInstance().getContext().getResources().getDisplayMetrics() );
    }
    //像素转换成dp
    public static int px2dp(int value ) {
        final float scale = AppContext.getInstance().getContext().getResources().getDisplayMetrics().density;
        return (int) (value / scale + 0.5f);
     }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int sp2px(float dpValue) {
        final float scale =  AppContext.getInstance().getContext().getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * double 保留小数后多少位
     * @param number
     * @param pointNumbser 小数点位数
     * @return
     */
     public static String doubleSavePointNumber(double number,int pointNumbser){
         if(UIUtils.isEmpty(number) || UIUtils.isEmpty(pointNumbser)){
             return "";
         }
         int pointLength=(number+"").length()-(number+"").indexOf(".")-1;
         if(pointLength<=pointNumbser ){
             String numberString = number+"";
             for(int i=0;i<pointNumbser-pointLength;i++){
                 numberString = numberString+"0";
             }
            return numberString;
         }

         BigDecimal result1 = new BigDecimal(Double.toString(number));
         return result1.setScale(pointNumbser, BigDecimal.ROUND_HALF_UP).toPlainString() ;
     }

    /**
     * double 转string取.0
     * @param intText
     * @return
     */
    public static String saveIntString(String intText){
        if(UIUtils.isEmpty(intText)){
            return "";
        }
        return intText.replace(".0","") ;
    }


    /**
     * 是否有网
     * @param context
     * @return
     */
    public static boolean isConnected(Context context) {
        ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = conn.getActiveNetworkInfo();
        return (info != null && info.isConnected());
    }

    /**
     * 显示日期
     * @return
     */
    public static String showDataByString(String text) {
        if(text==null)return "";
        if(text.length()>10){
            return text.substring(0,10);
        } else {
            return text;
        }
    }

    /**
     * 显示时间
     * @return
     */
    public static String showTimeByString(String text) {
        if(text==null)return "";
        if(text.length()>10){
            return text.substring(10);
        } else {
            return text;
        }
    }

    /**
     * 是否显示消息状态
     */
    public static boolean isShowTodayState(String textType) {
        Calendar calendar = Calendar.getInstance();
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        String taget = AppContext.getInstance().getAppPreferencesHelper().getKeyValue(textType+"");
        if(!isEmpty(taget)  && taget.equals(day+"")){
            return false;
        }else {
            return true;
        }
    }
    public static void setTodayState(String textType) {
        Calendar calendar = Calendar.getInstance();
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        AppContext.getInstance().getAppPreferencesHelper().setKeyValue(textType+"",day+"");

    }

    /**
     * 联系QQ
     * @param context
     * @return
     */
    public static boolean isQQInstall(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                //通过遍历应用所有包名进行判断
                if (pn.equals("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }


    /**
     * 检查是否拥有指定的所有权限
     */
    public static boolean checkPermissionAllGranted(Context context, String[] permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                // 只要有一个权限没有被授予, 则直接返回 false
                return false;
            }
        }
        return true;
    }

    /**
     * 判断定位服务是否开启
     *
     * @param context 上下文
     * @return true：开启；false：未开启
     */
    public static boolean isLocationEnabled(Context context) {
        int locationMode = 0;
        String locationProviders;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
            } catch (Settings.SettingNotFoundException e) {
                e.printStackTrace();
                return false;
            }
            return locationMode != Settings.Secure.LOCATION_MODE_OFF;
        } else {
            locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            return !TextUtils.isEmpty(locationProviders);
        }
    }

}
